package zack.gateway.core.executor;

import zack.gateway.core.datasource.Connection;
import zack.gateway.core.executor.result.SessionResult;
import zack.gateway.core.mapping.HttpStatement;
import zack.gateway.core.session.Configuration;
import zack.gateway.core.type.SimpleTypeRegistry;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Map;

/**抽象的执行器基类，定义执行流程
 * @author A1793
 */
public abstract class BaseExecutor implements Executor {
    private Logger logger = LoggerFactory.getLogger(BaseExecutor.class);
    protected Connection connection;
    protected Configuration configuration;

    public BaseExecutor(Connection connection, Configuration configuration) {
        this.connection = connection;
        this.configuration = configuration;
    }

    @Override
    public SessionResult exec(HttpStatement httpStatement, Map<String, Object> parameters) {
        //可以拓展参数处理
        String methodName = httpStatement.getMethodName();
        String[] parameterType = new String[]{httpStatement.getParameterType()};
        Object[] params = SimpleTypeRegistry.isSimpleType(httpStatement.getParameterType())?
                            parameters.values().toArray():new Object[]{parameters};

       try{
           Object result = doExecute(methodName, parameterType, params);
            return SessionResult.buildSuccess(result);
       }catch(Exception e){
           return SessionResult.buildError(e.getMessage());
       }

    }
    protected abstract Object doExecute(String methodName,String[] parameterTypes,Object[] params ) ;
}
